$(document).ready(function() {
    'use strict';

    // 全局变量
    let updateTimer = 0;
    let isFullscreen = false;
    let updateInterval = 0;
    let charts = {};

    // 初始化大屏
    function initDashboard() {
        initCharts();
        loadDashboardData();
        startAutoUpdate();
        updateCurrentTime();
        initTabSwitching();
    }

    // 初始化图表
    function initCharts() {
        // 检查DOM元素是否存在
        const chartElements = {
            'completionChart': document.getElementById('completionChart'),
            'overallProgressChart': document.getElementById('overallProgressChart'),
            'processPieChart': document.getElementById('processPieChart'),
            'employeeRankingChart': document.getElementById('employeeRankingChart'),
            'orderProgressChart': document.getElementById('orderProgressChart')
        };
        
        // 检查所有图表元素是否存在
        for (let key in chartElements) {
            if (!chartElements[key]) {
                console.error(`图表容器元素 ${key} 未找到，延迟初始化...`);
                setTimeout(initCharts, 100);
                return;
            }
        }

        // 完成率环形图
        charts.completionChart = echarts.init(chartElements.completionChart);
        const completionOption = {
            backgroundColor: 'transparent',
            series: [{
                type: 'pie',
                radius: ['60%', '80%'],
                center: ['50%', '50%'],
                data: [
                    { value: 0, name: '已完成', itemStyle: { color: '#4caf50' } },
                    { value: 100, name: '未完成', itemStyle: { color: '#e0e0e0' } }
                ],
                label: {
                    show: false
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        charts.completionChart.setOption(completionOption);

        // 整体进度柱状图
        charts.overallProgressChart = echarts.init(chartElements.overallProgressChart);
        const overallOption = {
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 }
            },
            yAxis: {
                type: 'value',
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 },
                splitLine: { lineStyle: { color: '#e0e0e0' } }
            },
            series: [{
                data: [],
                type: 'bar',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#00d4ff' },
                        { offset: 1, color: '#0066cc' }
                    ])
                },
                barWidth: '60%'
            }]
        };
        charts.overallProgressChart.setOption(overallOption);

        // 工序完成率饼图
        charts.processPieChart = echarts.init(chartElements.processPieChart);
        const processOption = {
            backgroundColor: 'transparent',
            title: {
                text: '工序完成率分布',
                left: 'center',
                top: '5%',
                textStyle: {
                    color: '#333',
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c}% ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: '5%',
                top: 'center',
                textStyle: { color: '#333', fontSize: 11 },
                itemWidth: 12,
                itemHeight: 8
            },
            series: [{
                name: '工序完成率',
                type: 'pie',
                radius: ['35%', '65%'],
                center: ['40%', '55%'],
                data: [],
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}: {c}%',
                    fontSize: 11,
                    color: '#333'
                },
                labelLine: {
                    show: true,
                    length: 12,
                    length2: 8
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        charts.processPieChart.setOption(processOption);

        // 员工完成率排行
        charts.employeeRankingChart = echarts.init(chartElements.employeeRankingChart);
        const employeeOption = {
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 },
                splitLine: { lineStyle: { color: '#e0e0e0' } }
            },
            yAxis: {
                type: 'category',
                data: [],
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 }
            },
            series: [{
                data: [],
                type: 'bar',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#4caf50' },
                        { offset: 1, color: '#2e7d32' }
                    ])
                },
                barWidth: '60%'
            }]
        };
        charts.employeeRankingChart.setOption(employeeOption);

        // 订单进度对比
        charts.orderProgressChart = echarts.init(chartElements.orderProgressChart);
        const orderOption = {
            backgroundColor: 'transparent',
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 }
            },
            yAxis: {
                type: 'value',
                axisLine: { lineStyle: { color: '#333' } },
                axisLabel: { color: '#333', fontSize: 12 },
                splitLine: { lineStyle: { color: '#e0e0e0' } }
            },
            series: [{
                name: '完成率',
                data: [],
                type: 'line',
                smooth: true,
                itemStyle: {
                    color: '#00d4ff'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 212, 255, 0.3)' },
                        { offset: 1, color: 'rgba(0, 212, 255, 0.1)' }
                    ])
                }
            }]
        };
        charts.orderProgressChart.setOption(orderOption);
    }

    // 加载大屏数据
    function loadDashboardData() {
        console.log('开始加载大屏数据...');
        
        // 调用真实API获取数据
        fetchRealData();
    }

    // 获取真实数据
    function fetchRealData() {
        console.log('开始获取数据...');
        
        // 获取生产计划进度数据
        $.ajax({
            url: '/api/scanwork/getProductionPlanProgress',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                console.log('API响应:', response);
                if (response && response.code === 1) {
                    console.log('数据更新开始...');
                    console.log('响应数据结构:', {
                        hasOverallStats: !!response.data.overallStats,
                        plansCount: response.data.plans ? response.data.plans.length : 0,
                        firstPlan: response.data.plans ? response.data.plans[0] : null
                    });
                    
                    updateKPIDataFromAPI(response.data);
                    updateChartsFromAPI(response.data);
                    updateTablesFromAPI(response.data);
                    console.log('数据更新完成');
                } else {
                    console.error('API返回错误:', response);
                    // 显示错误信息
                    $('.table tbody').html('<tr><td colspan="6" class="text-center text-danger">数据加载失败: ' + (response.msg || '未知错误') + '</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                console.error('获取生产计划进度数据失败:', error);
                console.error('响应状态:', xhr.status);
                console.error('响应文本:', xhr.responseText);
                
                // 显示错误信息
                $('.table tbody').html('<tr><td colspan="6" class="text-center text-danger">网络错误: ' + error + '</td></tr>');
            }
        });
    }

    // 更新KPI数据
    function updateKPIDataFromAPI(data) {
        if (!data || !data.overallStats) {
            console.error('KPI数据为空或格式错误:', data);
            return;
        }

        const stats = data.overallStats;
        console.log('更新KPI数据:', stats);
        
        // 更新KPI指标 - 按照API返回的字段名
        $('#totalOrders').text(stats.total_orders || 0);
        $('#totalPlans').text(stats.total_plans || 0);
        $('#totalAllocations').text(stats.total_allocations || 0);
        $('#totalQuantity').text(stats.total_quantity || 0);
        $('#completedQuantity').text(stats.completed_quantity || 0);
        
        // 使用API返回的完成率
        const completionRate = stats.overall_completion_rate || 0;
        $('#completionRate').text(completionRate.toFixed(1) + '%');

        // 更新完成率环形图
        if (charts.completionChart) {
            charts.completionChart.setOption({
                series: [{
                    data: [
                        { value: completionRate, name: '已完成', itemStyle: { color: '#4caf50' } },
                        { value: 100 - completionRate, name: '未完成', itemStyle: { color: '#e0e0e0' } }
                    ]
                }]
            });
        }

        // 添加数据更新动画
        $('.stats-card h1').addClass('data-updated');
        setTimeout(() => {
            $('.stats-card h1').removeClass('data-updated');
        }, 500);
        
        console.log('KPI数据更新完成');
    }

    // 更新图表数据
    function updateChartsFromAPI(data) {
        if (!data) return;

        // 更新整体进度柱状图 - 显示前10个计划
        if (data.plans && charts.overallProgressChart) {
            const topPlans = data.plans.slice(0, 10);
            const planNames = topPlans.map(plan => plan.order_name || plan.order_no || '未知订单');
            const completionRates = topPlans.map(plan => plan.completion_rate || 0);
            
            charts.overallProgressChart.setOption({
                xAxis: { data: planNames },
                series: [{ data: completionRates }]
            });
        }

        // 更新工序完成率饼图 - 使用真实数据
        if (charts.processPieChart && data.processStats) {
            // 过滤掉完成率为0的工序，避免标签重叠
            const processData = data.processStats
                .filter(process => process.completion_rate > 0)
                .map(process => ({
                    name: process.process_name,
                    value: process.completion_rate
                }));
            
            charts.processPieChart.setOption({
                series: [{ 
                    data: processData,
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c}%',
                        fontSize: 12,
                        color: '#333'
                    },
                    labelLine: {
                        show: true,
                        length: 15,
                        length2: 10
                    }
                }]
            });
        }

        // 更新员工完成率排行 - 使用真实数据
        if (charts.employeeRankingChart && data.employeeStats) {
            // 只显示前5名员工
            const topEmployees = data.employeeStats.slice(0, 5);
            const employeeNames = topEmployees.map(emp => emp.user_name);
            const employeeRates = topEmployees.map(emp => emp.completion_rate);
            
            charts.employeeRankingChart.setOption({
                yAxis: { data: employeeNames },
                series: [{ data: employeeRates }]
            });
        }

        // 更新订单进度对比 - 显示前8个订单
        if (data.plans && charts.orderProgressChart) {
            const topOrders = data.plans.slice(0, 8);
            const orderNames = topOrders.map(plan => plan.order_name || plan.order_no);
            const orderRates = topOrders.map(plan => plan.completion_rate || 0);
            
            charts.orderProgressChart.setOption({
                xAxis: { data: orderNames },
                series: [{ data: orderRates }]
            });
        }
    }

    // 更新表格数据
    function updateTablesFromAPI(data) {
        if (!data) {
            console.error('表格数据为空');
            return;
        }

        console.log('开始更新表格数据，plans数量:', data.plans ? data.plans.length : 0);

        // 更新订单统计表格 - 从plans数据中按订单分组
        if (data.plans && data.plans.length > 0) {
            console.log('处理订单统计表格...');
            const orderMap = {};
            data.plans.forEach(plan => {
                const orderKey = plan.order_id;
                if (!orderMap[orderKey]) {
                    orderMap[orderKey] = {
                        order_name: plan.order_name || '-',
                        order_no: plan.order_no || '-',
                        total_plans: 0,
                        total_quantity: 0,
                        completed_quantity: 0
                    };
                }
                orderMap[orderKey].total_plans++;
                orderMap[orderKey].total_quantity += plan.total_quantity || 0;
                orderMap[orderKey].completed_quantity += plan.actual_quantity || 0;
            });

            console.log('订单分组结果:', orderMap);

            const tbody = $('#orderStatsTable');
            if (tbody.length === 0) {
                console.error('找不到订单统计表格元素 #orderStatsTable');
                return;
            }
            
            tbody.empty();
            
            Object.values(orderMap).forEach(order => {
                const completionRate = order.total_quantity > 0 ? 
                    Math.round((order.completed_quantity / order.total_quantity) * 100) : 0;
                const row = `
                    <tr>
                        <td>${order.order_name}</td>
                        <td>${order.order_no}</td>
                        <td><span class="badge bg-blue">${order.total_plans}</span></td>
                        <td>${order.total_quantity}</td>
                        <td>${order.completed_quantity}</td>
                        <td>
                            <div class="progress progress-xs">
                                <div class="progress-bar bg-green" style="width: ${completionRate}%"></div>
                            </div>
                            <span class="text-muted">${completionRate}%</span>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
            
            console.log('订单统计表格更新完成，共', Object.keys(orderMap).length, '个订单');
        } else {
            console.error('没有找到plans数据');
        }

        // 更新产品统计表格 - 从plans数据中按产品分组
        if (data.plans && data.plans.length > 0) {
            console.log('处理产品统计表格...');
            const productMap = {};
            data.plans.forEach(plan => {
                const productKey = plan.product_id;
                if (!productMap[productKey]) {
                    productMap[productKey] = {
                        product_name: plan.product_name || '-',
                        total_plans: 0,
                        total_quantity: 0,
                        completed_quantity: 0
                    };
                }
                productMap[productKey].total_plans++;
                productMap[productKey].total_quantity += plan.total_quantity || 0;
                productMap[productKey].completed_quantity += plan.actual_quantity || 0;
            });

            const tbody = $('#productStatsTable');
            if (tbody.length === 0) {
                console.error('找不到产品统计表格元素 #productStatsTable');
                return;
            }
            
            tbody.empty();
            
            Object.values(productMap).forEach(product => {
                const completionRate = product.total_quantity > 0 ? 
                    Math.round((product.completed_quantity / product.total_quantity) * 100) : 0;
                const row = `
                    <tr>
                        <td><strong>${product.product_name}</strong></td>
                        <td>${product.total_plans}</td>
                        <td>${product.total_quantity}</td>
                        <td>${product.completed_quantity}</td>
                        <td>
                            <div class="progress progress-sm">
                                <div class="progress-bar bg-blue" style="width: ${completionRate}%"></div>
                            </div>
                            <span class="text-muted">${completionRate}%</span>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
            
            console.log('产品统计表格更新完成，共', Object.keys(productMap).length, '个产品');
        }

        // 更新工序统计表格 - 使用API返回的工序统计数据
        console.log('处理工序统计表格...');
        const processTbody = $('#processStatsTable');
        if (processTbody.length === 0) {
            console.error('找不到工序统计表格元素 #processStatsTable');
        } else {
            processTbody.empty();
            
            // 使用API返回的工序统计数据
            if (data.processStats && data.processStats.length > 0) {
                console.log('工序统计数据:', data.processStats);
                
                data.processStats.forEach(process => {
                    const row = `
                        <tr>
                            <td>${process.process_name}</td>
                            <td><span class="badge bg-yellow">${process.allocation_count}</span></td>
                            <td>${process.total_quantity}</td>
                            <td>${process.completed_quantity}</td>
                            <td>
                                <div class="progress progress-xs">
                                    <div class="progress-bar bg-green" style="width: ${process.completion_rate}%"></div>
                                </div>
                                <span class="text-muted">${process.completion_rate}%</span>
                            </td>
                        </tr>
                    `;
                    processTbody.append(row);
                });
                
                console.log('工序统计表格更新完成，共', data.processStats.length, '个工序');
            } else {
                processTbody.append('<tr><td colspan="5" class="text-center text-muted">暂无工序数据</td></tr>');
                console.log('没有工序统计数据');
            }
        }

        // 更新员工统计表格 - 使用API返回的员工统计数据
        console.log('处理员工统计表格...');
        const employeeTbody = $('#employeeStatsTable');
        if (employeeTbody.length === 0) {
            console.error('找不到员工统计表格元素 #employeeStatsTable');
        } else {
            employeeTbody.empty();
            
            // 使用API返回的员工统计数据
            if (data.employeeStats && data.employeeStats.length > 0) {
                console.log('员工统计数据:', data.employeeStats);
                
                data.employeeStats.forEach(employee => {
                    const row = `
                        <tr>
                            <td>${employee.user_name}</td>
                            <td><span class="badge bg-purple">${employee.allocation_count}</span></td>
                            <td>${employee.total_quantity}</td>
                            <td>${employee.completed_quantity}</td>
                            <td>
                                <div class="progress progress-xs">
                                    <div class="progress-bar bg-green" style="width: ${employee.completion_rate}%"></div>
                                </div>
                                <span class="text-muted">${employee.completion_rate}%</span>
                            </td>
                        </tr>
                    `;
                    employeeTbody.append(row);
                });
                
                console.log('员工统计表格更新完成，共', data.employeeStats.length, '个员工');
            } else {
                employeeTbody.append('<tr><td colspan="5" class="text-center text-muted">暂无员工数据</td></tr>');
                console.log('没有员工统计数据');
            }
        }
        
        console.log('所有表格数据更新完成');
    }

    // 自动更新状态
    let autoUpdateEnabled = true;

    // 开始自动更新
    function startAutoUpdate() {
        if (autoUpdateEnabled) {
            updateInterval = setInterval(() => {
                loadDashboardData();
                updateCurrentTime();
            }, 6000000); // 每30秒更新一次
        }
    }

    // 手动刷新
    window.manualRefresh = function() {
        loadDashboardData();
        updateCurrentTime();
    }

    // 切换自动更新
    window.toggleAutoUpdate = function() {
        autoUpdateEnabled = !autoUpdateEnabled;
        
        if (autoUpdateEnabled) {
            // 启用自动更新
            startAutoUpdate();
            $('#autoToggleIcon').removeClass('fa-play').addClass('fa-pause');
            $('#autoToggleText').text('暂停');
        } else {
            // 停止自动更新
            if (updateInterval) {
                clearInterval(updateInterval);
                updateInterval = null;
            }
            $('#autoToggleIcon').removeClass('fa-pause').addClass('fa-play');
            $('#autoToggleText').text('开始');
        }
    }

    // 更新当前时间
    function updateCurrentTime() {
        const now = new Date();
        const seconds = Math.floor((Date.now() - updateTimer) / 1000);
        $('#updateTime').text(seconds + 's');
    }

    // 全屏切换
    window.toggleFullscreen = function() {
        if (!isFullscreen) {
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen();
            }
            isFullscreen = true;
            $('.btn-exit-fullscreen i').removeClass('fa-expand').addClass('fa-compress');
            $('.btn-exit-fullscreen').html('<i class="fa fa-compress"></i> 退出全屏');
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
            isFullscreen = false;
            $('.btn-exit-fullscreen i').removeClass('fa-compress').addClass('fa-expand');
            $('.btn-exit-fullscreen').html('<i class="fa fa-expand"></i> 全屏');
        }
    }

    // 监听全屏状态变化
    document.addEventListener('fullscreenchange', function() {
        isFullscreen = !!document.fullscreenElement;
    });

    // 窗口大小变化时重新调整图表
    window.addEventListener('resize', function() {
        for (let key in charts) {
            if (charts[key]) {
                charts[key].resize();
            }
        }
    });

    // 初始化标签页切换功能
    function initTabSwitching() {
        console.log('初始化标签页切换功能...');
        
        // 使用更简单的方法处理标签页切换
        $('.nav-tabs a').on('click', function (e) {
            e.preventDefault();
            const target = $(this).attr('href');
            console.log('标签页点击:', target);
            
            // 移除所有活动状态
            $('.nav-tabs li').removeClass('active');
            $('.tab-pane').removeClass('active');
            
            // 添加当前活动状态
            $(this).parent().addClass('active');
            $(target).addClass('active');
            
            console.log('标签页切换到:', target);
            
            // 强制重新渲染表格（如果需要）
            setTimeout(() => {
                console.log('当前活动标签页:', $('.tab-pane.active').attr('id'));
            }, 100);
        });
        
        console.log('标签页切换功能初始化完成');
        
        // 测试标签页切换功能
        setTimeout(() => {
            console.log('测试标签页切换...');
            console.log('当前活动标签页:', $('.tab-pane.active').attr('id'));
            console.log('所有标签页:', $('.tab-pane').map(function() { return this.id; }).get());
        }, 1000);
    }

    // 初始化
    initDashboard();
    updateTimer = Date.now();
});